<template>
  <div class="roll-management-container">
    <h2>真题试卷管理</h2>
    
    <!-- 查询条件表单 -->
    <el-form :model="queryForm" :inline="true" class="query-form">
      <el-form-item label="年份">
        <el-select v-model="queryForm.examYear" placeholder="请选择年份" clearable style="width: 150px">
          <el-option
            v-for="year in years"
            :key="year"
            :label="year"
            :value="year"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="试卷类型">
        <el-select v-model="queryForm.typeId" placeholder="请选择试卷类型" clearable style="width: 150px" >
          <el-option
            v-for="type in paperTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="fetchQuestions" :loading="loading">
          查询
        </el-button>
      </el-form-item>
    </el-form>
    
    <!-- 试卷展示区域 -->
    <div v-if="questions.length > 0" class="paper-container">
      <div class="paper-header">
        <h3>{{ queryForm.examYear }}年 数学{{ getPaperTypeName(queryForm.typeId) }}真题</h3>
        <el-button 
          type="primary" 
          @click="toggleEditMode" 
          class="edit-btn"
          :icon="editMode ? 'el-icon-close' : 'el-icon-edit'"
        >
          {{ editMode ? '退出编辑' : '编辑试卷' }}
        </el-button>
      </div>
      
      <!-- 题目列表 -->
      <div class="questions-container">
        <!-- 选择题部分 -->
        <div v-if="hasChoiceQuestions" class="question-section">
          <h4>一、选择题</h4>
          <div 
            v-for="(question, index) in choiceQuestions" 
            :key="question.questionId" 
            class="question-item"
          >
            <div class="question-content">
              <span class="question-number">{{ index + 1 }}.</span>
              <el-input 
                v-if="editMode" 
                v-model="question.content" 
                type="textarea"
                :rows="2"
                class="content-input"
              />
              <span v-else v-html="formatQuestionContent(question.content)"></span>
            </div>
            
            <!-- 选择题选项（确保optionsArray正确解析） -->
            <div v-if="question.optionsArray && question.optionsArray.length > 0" class="question-options">
              <div 
                v-for="(option, optIndex) in question.optionsArray" 
                :key="optIndex"
                class="option-item"
              >
                <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}.</span>
                <el-input 
                  v-if="editMode" 
                  v-model="question.optionsArray[optIndex]" 
                  class="option-input"
                  @change="updateOptions(question)"
                />
                <span v-else v-html="formatQuestionContent(option)"></span>
              </div>
            </div>
            
            <!-- 答案和解析 -->
            <div class="question-answer">
              <el-collapse>
                <el-collapse-item title="查看答案与解析">
                  <div class="answer-row">
                    <strong>答案：</strong> 
                    <el-input 
                      v-if="editMode" 
                      v-model="question.choiceAnswer" 
                      class="answer-input"
                      placeholder="请输入答案"
                    />
                    <span v-else>{{ question.choiceAnswer }}</span>
                  </div>
                  <div class="analysis-row">
                    <strong>解析：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.choiceAnalysis"
                      type="textarea"
                      :rows="3"
                      class="analysis-input"
                      placeholder="请输入解析"
                    />
                    <span v-else v-html="formatQuestionContent(question.choiceAnalysis)"></span>
                  </div>
                  <div v-if="editMode" class="action-buttons">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="saveQuestion(question)"
                      :loading="question.saving"
                    >
                      保存修改
                    </el-button>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
        
        <!-- 填空题部分 -->
        <div v-if="hasFillBlankQuestions" class="question-section">
          <h4>二、填空题</h4>
          <div 
            v-for="(question, index) in fillBlankQuestions" 
            :key="question.questionId" 
            class="question-item"
          >
            <div class="question-content">
              <span class="question-number">{{ index + 1 }}.</span>
              <el-input 
                v-if="editMode" 
                v-model="question.content" 
                type="textarea"
                :rows="2"
                class="content-input"
              />
              <span v-else v-html="formatFillBlankContent(question)"></span>
            </div>
            
            <!-- 答案和解析 -->
            <div class="question-answer">
              <el-collapse>
                <el-collapse-item title="查看答案与解析">
                  <div class="answer-row">
                    <strong>填空位置：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.blanks"
                      type="textarea"
                      :rows="1"
                      class="blanks-input"
                      placeholder="请输入填空位置，JSON格式"
                    />
                    <span v-else>{{ question.blanks }}</span>
                  </div>
                  <div class="answer-row">
                    <strong>答案模板：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.answerTemplate"
                      type="textarea"
                      :rows="2"
                      class="template-input"
                      placeholder="请输入答案模板"
                    />
                    <span v-else v-html="formatQuestionContent(question.answerTemplate)"></span>
                  </div>
                  <div class="analysis-row">
                    <strong>解析：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.fillblankAnalysis"
                      type="textarea"
                      :rows="3"
                      class="analysis-input"
                      placeholder="请输入解析"
                    />
                    <span v-else v-html="formatQuestionContent(question.fillblankAnalysis)"></span>
                  </div>
                  <div v-if="editMode" class="action-buttons">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="saveQuestion(question)"
                      :loading="question.saving"
                    >
                      保存修改
                    </el-button>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
        
        <!-- 主观题部分 -->
        <div v-if="hasSubjectiveQuestions" class="question-section">
          <h4>三、主观题</h4>
          <div 
            v-for="(question, index) in subjectiveQuestions" 
            :key="question.questionId" 
            class="question-item"
          >
            <div class="question-content">
              <span class="question-number">{{ index + 1 }}.</span>
              <el-input 
                v-if="editMode" 
                v-model="question.content" 
                type="textarea"
                :rows="3"
                class="content-input"
              />
              <span v-else v-html="formatQuestionContent(question.content)"></span>
            </div>
            
            <!-- 答案和解析 -->
            <div class="question-answer">
              <el-collapse>
                <el-collapse-item title="查看答案与解析">
                  <div class="answer-row">
                    <strong>参考答案：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.referenceAnswer"
                      type="textarea"
                      :rows="4"
                      class="reference-input"
                      placeholder="请输入参考答案"
                    />
                    <span v-else v-html="formatQuestionContent(question.referenceAnswer)"></span>
                  </div>
                  <div class="analysis-row">
                    <strong>解析：</strong>
                    <el-input
                      v-if="editMode"
                      v-model="question.subjectiveAnalysis"
                      type="textarea"
                      :rows="3"
                      class="analysis-input"
                      placeholder="请输入解析"
                    />
                    <span v-else v-html="formatQuestionContent(question.subjectiveAnalysis)"></span>
                  </div>
                  <div v-if="editMode" class="action-buttons">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="saveQuestion(question)"
                      :loading="question.saving"
                    >
                      保存修改
                    </el-button>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 无数据提示 -->
    <div v-else-if="!loading" class="empty-tip">
      <el-empty description="请选择年份和试卷类型查询真题"></el-empty>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus'; 
import 'katex/dist/katex.min.css';
import katex from 'katex';
import MarkdownIt from 'markdown-it';
import markdownItKatex from 'markdown-it-katex';

export default {
  name: 'RollManagement',
  data() {
    return {
      queryForm: {
        examYear: null,
        typeId: 1 
      },
      years: this.generateYears(2000, new Date().getFullYear()),
      paperTypes: [
        { label: '数学一', value: 1 },
        { label: '数学二', value: 2 },
        { label: '数学三', value: 3 }
      ],
      questions: [],
      loading: false,
      editMode: false,
      // 配置markdown-it和KaTeX
      md: new MarkdownIt({
        html: true,        // 允许HTML标签
        breaks: true,      // 转换换行符
        linkify: true      // 自动转换链接
      }).use(markdownItKatex, {
        // KaTeX配置选项
        throwOnError: false,
        errorColor: '#cc0000',
        strict: false,
        trust: true,
        output: 'html'
      })
    };
  },
  created() {
    this.queryForm.examYear = this.years[0];
    this.fetchQuestions();
  },
  computed: {
    choiceQuestions() {
      return this.questions.filter(q => 
        q.questionType === 'single_choice' || q.questionType === 'multiple_choice'
      );
    },
    fillBlankQuestions() {
      return this.questions.filter(q => q.questionType === 'fill_in_the_blank');
    },
    subjectiveQuestions() {
      return this.questions.filter(q => q.questionType === 'subjective');
    },
    hasChoiceQuestions() {
      return this.choiceQuestions.length > 0;
    },
    hasFillBlankQuestions() {
      return this.fillBlankQuestions.length > 0;
    },
    hasSubjectiveQuestions() {
      return this.subjectiveQuestions.length > 0;
    }
  },
  methods: {
    // 格式化题目内容 - 使用KaTeX和markdown-it处理
    formatQuestionContent(content) {
      if (!content) return '';
      
      try {
        // 预处理内容
        let processedContent = content
          .replace(/\\n/g, '\n')  // 处理换行符
          .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
          .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
            // 处理块级数学公式 $$...$$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: true,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX block formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$$${formula}$$</span>`;
            }
          })
          .replace(/\$([^$\n]+)\$/g, (match, formula) => {
            // 处理行内数学公式 $...$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: false,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$${formula}$</span>`;
            }
          })
          .replace(/###DOLLAR###/g, '$');  // 恢复转义的美元符号
        
        // 使用markdown-it处理其他格式
        const htmlContent = this.md.render(processedContent);
        
        return htmlContent;
      } catch (error) {
        console.error('formatQuestionContent error:', error);
        return content.replace(/\\n/g, '<br>');
      }
    },
    
    generateYears(start, end) {
      const years = [];
      for (let i = end; i >= start; i--) {
        years.push(i);
      }
      return years;
    },
    
    getPaperTypeName(typeId) {
      const type = this.paperTypes.find(t => t.value === typeId);
      return type ? type.label.replace('数学', '') : '';
    },
    
    parseOptions(options) {
      try {
        if (!options) return [];
        
        if (Array.isArray(options)) return options;
        
        const parsed = JSON.parse(options);
        
        if (Array.isArray(parsed)) {
          return parsed;
        } else if (typeof parsed === 'object' && parsed !== null) {
          return Object.values(parsed);
        } else if (typeof parsed === 'string') {
          return parsed.split('|'); 
        }
        
        return [];
      } catch (e) {
        console.error('解析选项出错:', e);
        return [];
      }
    },
    
    updateOptions(question) {
      try {
        const optionsObj = {};
        question.optionsArray.forEach((opt, index) => {
          optionsObj[String.fromCharCode(65 + index)] = opt;
        });
        question.options = JSON.stringify(optionsObj);
      } catch (e) {
        console.error('更新选项出错:', e);
        ElMessage.error('选项格式错误，请检查输入');
      }
    },
    
    formatFillBlankContent(question) {
      if (!question.blanks) return this.formatQuestionContent(question.content);
      
      try {
        const blanks = JSON.parse(question.blanks);
        let content = question.content;
        
        blanks.forEach(pos => {
          const blank = `<span class="blank-space">(${pos})</span>`;
          content = content.replace(`{{${pos}}}`, blank);
        });
        
        return this.formatQuestionContent(content);
      } catch (e) {
        console.error('解析填空题填空位置出错:', e);
        ElMessage.error('填空题格式错误，请检查输入');
        return this.formatQuestionContent(question.content);
      }
    },
    
    toggleEditMode() {
      this.editMode = !this.editMode;
      if (!this.editMode) {
        this.fetchQuestions(); 
      }
    },
    
    async fetchQuestions() {
      if (!this.queryForm.examYear || !this.queryForm.typeId) {
        ElMessage.warning('请选择年份和试卷类型');
        return;
      }
      
      this.loading = true;
      try {
        const response = await axios.get('/roll/questions', {
          params: {
            examYear: this.queryForm.examYear,
            typeId: this.queryForm.typeId
          }
        });
        
        this.questions = response.data.map(question => {
          const q = {
            ...question,
            saving: false,
            optionsArray: this.parseOptions(question.options) 
          };
          return q;
        });
        
        if (response.data.length === 0) {
          ElMessage.info('未查询到相关题目');
        }
      } catch (error) {
        console.error('获取题目失败:', error);
        ElMessage.error('网络异常或接口错误，请重试');
      } finally {
        this.loading = false;
      }
    },
    
    async saveQuestion(question) {
        try {
            question.saving = true;
            
            const requestData = {
                questionId: question.questionId,
                questionType: question.questionType,
                content: question.content,
                options: question.options, 
                difficulty: question.difficulty || '', 
                examYear: question.examYear || '',
                typeId: question.typeId || 1,
                chapterId: question.chapterId || '',
                keyword: question.keyword || '',
                choiceAnswer: question.choiceAnswer || '',
                choiceAnalysis: question.choiceAnalysis || '',
                answerTemplate: question.answerTemplate || '',
                blanks: question.blanks || '',
                fillblankAnalysis: question.fillblankAnalysis || '',
                referenceAnswer: question.referenceAnswer || '',
                subjectiveAnalysis: question.subjectiveAnalysis || ''
            };
            
            const res = await axios.put('/roll/answer', requestData);
            
            if (res.data.code === 200) {
                ElMessage.success(res.data.message || '保存成功');
                const updatedQuestion = await this.fetchUpdatedQuestion(question.questionId);
                Object.assign(question, updatedQuestion);
            } else {
                ElMessage.error(res.data.message || '保存失败');
            }
        } catch (error) {
            console.error('保存失败:', error);
            const errorMsg = error.response?.data?.message || 
                            error.response?.data || 
                            error.message || 
                            '未知错误';
            ElMessage.error(`保存失败: ${errorMsg}`);
        } finally {
            question.saving = false;
        }
    },
        
    async fetchUpdatedQuestion(questionId) {
        try {
            const response = await axios.get('/roll/questions', {
                params: {
                    examYear: this.queryForm.examYear,
                    typeId: this.queryForm.typeId
                }
            });
            return response.data.find(q => q.questionId === questionId);
        } catch (error) {
            console.error('获取更新后的题目失败:', error);
            return null;
        }
    }
  }
};
</script>

<style scoped>
.roll-management-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.roll-management-container h2 {
  color: #303133;
  margin-bottom: 24px;
  text-align: center;
  font-size: 24px;
  font-weight: 500;
}

.query-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.query-form .el-form-item {
  margin-bottom: 0;
}

.paper-container {
  margin-top: 20px;
  border-radius: 4px;
  padding: 24px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.paper-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
}

.paper-header h3 {
  color: #303133;
  font-size: 20px;
  margin: 0;
}

.edit-btn {
  position: absolute;
  right: 0;
  top: 0;
}

.question-section {
  margin-bottom: 40px;
}

.question-section h4 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.question-item {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px dashed #e6e6e6;
}

.question-item:last-child {
  border-bottom: none;
}

.question-content {
  margin-bottom: 16px;
  line-height: 1.6;
  font-size: 16px;
}

.question-content .content-input {
  width: 100%;
}

.question-number {
  font-weight: bold;
  margin-right: 8px;
  color: #409eff;
}

.question-options {
  margin: 16px 0 16px 24px;
}

.option-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.option-item .option-letter {
  margin-right: 8px;
  font-weight: bold;
  min-width: 24px;
  color: #606266;
}

.option-item .option-input {
  width: 400px;
  margin-left: 8px;
}

.question-answer {
  margin-top: 16px;
}

.question-answer .answer-row {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.question-answer .answer-row strong {
  min-width: 80px;
  display: inline-block;
}

.question-answer .answer-row .answer-input {
  width: 120px;
}

.question-answer .answer-row .blanks-input,
.question-answer .answer-row .template-input,
.question-answer .answer-row .reference-input {
  width: 100%;
}

.question-answer .analysis-row {
  margin-top: 12px;
  display: flex;
  align-items: flex-start;
}

.question-answer .analysis-row strong {
  min-width: 80px;
  display: inline-block;
}

.question-answer .analysis-row .analysis-input {
  width: 100%;
}

.question-answer .action-buttons {
  margin-top: 16px;
  text-align: right;
}

.empty-tip {
  margin-top: 60px;
  text-align: center;
  background: #fff;
  padding: 40px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-collapse {
  border: none;
}

.el-collapse .el-collapse-item__header {
  font-size: 15px;
  color: #409eff;
  border-bottom: none;
  padding-left: 10px;
}

.el-collapse .el-collapse-item__wrap {
  border-bottom: none;
  background-color: #f9fafc;
  padding: 12px;
  border-radius: 4px;
}

/* KaTeX样式优化 */
.question-content :deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
}

.question-content :deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
}

.question-content :deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 选项中的KaTeX样式 */
.option-item :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.option-item :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
}

/* KaTeX全局样式优化 */
:deep(.katex) {
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}
</style>